package com.gqj.meter.service.impl;

import com.gqj.common.constant.UserConstants;
import com.gqj.common.exception.ServiceException;
import com.gqj.common.utils.StringUtils;
import com.gqj.common.utils.bean.BeanValidators;
import com.gqj.meter.domain.MdMeter;
import com.gqj.meter.mapper.MdMeterMapper;
import com.gqj.meter.service.IMdMeterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.List;
import java.util.Map;

/**
 * 电能表Service业务层处理
 *
 * @author lxq
 * @date lxq-02-10
 */
@Service
public class MdMeterServiceImpl implements IMdMeterService {
    @Autowired
    private MdMeterMapper mdMeterMapper;
    private static final Logger log = LoggerFactory.getLogger(MdMeterServiceImpl.class);
    @Autowired
    protected Validator validator;

    /**
     * 查询电能表
     *
     * @param meterId 电能表主键
     * @return 电能表
     */
    @Override
    public MdMeter selectMdMeterByMeterId(Long meterId) {
        return mdMeterMapper.selectMdMeterByMeterId(meterId);
    }

    /**
     * 查询电能表列表
     *
     * @param mdMeter 电能表
     * @return 电能表
     */
    @Override
    public List<MdMeter> selectMdMeterList(MdMeter mdMeter) {
        return mdMeterMapper.selectMdMeterList(mdMeter);
    }

    /**
     * 新增电能表
     *
     * @param mdMeter 电能表
     * @return 结果
     */
    @Override
    public int insertMdMeter(MdMeter mdMeter) {
        return mdMeterMapper.insertMdMeter(mdMeter);
    }

    /**
     * 修改电能表
     *
     * @param mdMeter 电能表
     * @return 结果
     */
    @Override
    public int updateMdMeter(MdMeter mdMeter) {
        mdMeter.setMeterNo(mdMeter.getRfidNo());
        return mdMeterMapper.updateMdMeter(mdMeter);
    }

    /**
     * 批量删除电能表
     *
     * @param meterIds 需要删除的电能表主键
     * @return 结果
     */
    @Override
    public int deleteMdMeterByMeterIds(Long[] meterIds) {
        return mdMeterMapper.deleteMdMeterByMeterIds(meterIds);
    }

    /**
     * 删除电能表信息
     *
     * @param meterId 电能表主键
     * @return 结果
     */
    @Override
    public int deleteMdMeterByMeterId(Long meterId) {
        return mdMeterMapper.deleteMdMeterByMeterId(meterId);
    }

    /**
     * 校验资产编号码是否唯一
     *
     * @param mdMeter 电能表
     * @return 结果
     */
    public String checkMeterNoUnique(MdMeter mdMeter) {
        Long meterId = StringUtils.isNull(mdMeter.getMeterId()) ? -1L : mdMeter.getMeterId();
        MdMeter info = mdMeterMapper.checkMeterNoUnique(mdMeter.getMeterNo());
        if (StringUtils.isNotNull(info) && info.getMeterId().longValue() != meterId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验rfid编号/条形码是否唯一
     *
     * @param mdMeter 电能表
     * @return 结果
     */
    public String checkRfidNoUnique(MdMeter mdMeter) {
        Long meterId = StringUtils.isNull(mdMeter.getMeterId()) ? -1L : mdMeter.getMeterId();
        MdMeter info = mdMeterMapper.checkRfidNoUnique(mdMeter.getRfidNo());
        if (StringUtils.isNotNull(info) && info.getMeterId().longValue() != meterId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 导入电能表数据
     *
     * @param meterList       电能表列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importMeter(List<MdMeter> meterList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(meterList) || meterList.size() == 0) {
            throw new ServiceException("导入电能表不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (MdMeter meter : meterList) {
            try {
                BeanValidators.validateWithException(validator, meter);
                // 验证是否存在这个数据
                MdMeter m = mdMeterMapper.selectMdMeterByRfidNo(meter.getRfidNo());
                if (StringUtils.isNull(m)) {
                    meter.setServiceStatus("00");
                    this.insertMdMeter(meter);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、电能表 " + meter.getRfidNo() + " 导入成功");
                } else if (isUpdateSupport) {
                    meter.setMeterId(m.getMeterId());
                    this.updateMdMeter(meter);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、电能表 " + meter.getRfidNo() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、电能表 " + meter.getRfidNo() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、电能表 " + meter.getRfidNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    //查询资产统计信息
    @Override
    public List<Map<String, Object>> getMaterialStatisticsInfo(String curStatusCode) {
        return mdMeterMapper.getMaterialInfo(curStatusCode);
    }

    //查询业务状态数量
    @Override
    public int[] getServiceStatusNum() {
        Map<String, Object> map = mdMeterMapper.getServiceStatusNum();

        int[] counts = new int[6];
        counts[0] = ((Long) map.get("count_00")).intValue();
        counts[1] = ((Long) map.get("count_01")).intValue();
        counts[2] = ((Long) map.get("count_02")).intValue();
        counts[3] = ((Long) map.get("count_03")).intValue();
        counts[4] = ((Long) map.get("count_04")).intValue();
        counts[5] = ((Long) map.get("count_05")).intValue();
        return counts;
    }

    /**
     * 通过rfidCode查询电能表信息
     *
     * @param rfidNos 电能表主键
     * @return 电能表
     */
    @Override
    public List<MdMeter> selectMdMeterByRfidBath(String[] rfidNos){
        return mdMeterMapper.selectMdMeterByRfidBath(rfidNos);
    }
}
